﻿String.format = function (text) {
    if (arguments.length <= 1) {
        return text;
    }
    var tokenCount = arguments.length - 2;
    for (var token = 0; token <= tokenCount; token++) {
        text = text.replace(new RegExp("\\{" + token + "\\}", "gi"), arguments[token + 1]);
    }
    return text;
};


//SETTINGs
var sohaEmbed_SourceDomain = "http://soha.vn";
var sohaEmbed_GenK_CssSource = "/www/genk/genk-style.css";
var sohaEmbed_GenK_utmSource = "?utm_source=GenK&utm_medium=GenKEmbed&utm_campaign=GenKBoxEmbed";
var sohaEmbed_GenK_headUtmSource = "?utm_source=GenK&utm_medium=Head_GenKEmbed&utm_campaign=Head_GenKBoxEmbed";
var sohaEmbed_Genk_BoxID = "sohaEmbed_GenK";
//



var hSohaEmbed = new function () {

    this.imageWidth = 215;
    this.imageHeight = 135;
    this.top = 28;
    this.type = 2;

    this.sohaSlideWrapper = "hSohaSlideWrapper";


    //BIND DATA
    bindData = function (data) {
        data = eval('(' + data + ')');
        if (data != null && data.length > 0) {
            var embedHtml = '';
            var format = "<li class=\"{4}\"><a href=\"soha.vn{0}\" target=\"_blank\" title=\"{2}\">{3}<p>{1}</p></a></li>";
            var firstCssClass = "hSohaEmbed_mgl10";
            var cssClass = "hSohaEmbed_mgl18";

            for (var i = 0; i < data.length; i++) {

                var item = data[i];
                if (i % 4 == 0) {
                    embedHtml += "<ul class=\"hSohaEmbed_box-sohact\">";
                }

                embedHtml += String.format(
                        format,
                        item["Url"] + sohaEmbed_GenK_utmSource,
                        item["Title"],
                        item["EncodedTitle"],
                        item["FormatedImage"],
                        cssClass);


                if (((i + 1) % 4) == 0 || (i + 1) == data.length) {
                    embedHtml += "</ul>";
                }
            }

            $("#hSohaSlideWrapper").html(embedHtml);
            $("#" + sohaEmbed_Genk_BoxID).show();
            $("#" + sohaEmbed_Genk_BoxID + " a:not('.rowsprite')").attr("target", "_blank");
            var cssSourceFormat = "<link href=\"{0}{1}\" rel=\"stylesheet\" type=\"text/css\" />";
            $("head").append(String.format(cssSourceFormat, sohaEmbed_SourceDomain, sohaEmbed_GenK_CssSource));
        }
    };


    //GET DATA 
    this.getData = function () {
        var urlFormat = "/Services/GetEmbedData.ashx?Top={0}&ImageWidth={1}&ImageHeight={2}&Type={3}";

        var url = sohaEmbed_SourceDomain + String.format(urlFormat, this.top, this.imageWidth, this.imageHeight, this.type);

        var ohtml = '';
        ohtml += "<div id=\"" + sohaEmbed_Genk_BoxID + "\" class=\"hSohaEmbed_box-soha\">";
        ohtml += "<a href=\"http://soha.vn" + sohaEmbed_GenK_headUtmSource + "\" class=\"hSohaEmbed_box-shtt\"><span class=\"hSohaEmbed_box-sohatt\"></span>";
        ohtml += "<p>";
        ohtml += "TIN HOT TỪ SOHA.VN</p>";
        ohtml += "</a>";
        ohtml += "<div class=\"hSohaEmbed_boxsh-row\">";
        ohtml += "<p id=\"hSohaEmbed_SlideCounter\">";
        ohtml += "</p>";
        ohtml += "<a id=\"hSohaEmbed_btnPre\" href=\"javascript:void(0);\" class=\"hSohaEmbed_prebt rowsprite\"></a>";
        ohtml += "<a id=\"hSohaEmbed_btnNext\" href=\"javascript:void(0);\" class=\"hSohaEmbed_nextbt-active rowsprite\">";
        ohtml += "</a>";
        ohtml += "</div>";
        ohtml += "<div id=\"hSohaSlideWrapper\">";
        ohtml += "</div>";
        ohtml += "</div>";

        document.write(ohtml);
        $("#" + sohaEmbed_Genk_BoxID).hide();

        $.ajax({
            type: 'GET',
            url: url,
            dataType: "jsonp",
            success: function (response) {
                if (JSON.stringify(response.Success)) {
                    bindData(JSON.stringify(response.Data));
                    makeItSlideable();
                }
            },
            error: function (e) {
                console.log(JSON.stringify(e));
            }
        });
    }


    //MAKE IT SLIDE
    var makeItSlideable = function () {

        var currentPosition = 0;
        var slideWidth = 973;
        var displayNum = 1;
        var speed = 8000;


        var slides = $(".hSohaEmbed_box-sohact");


        if (slides.length > 0) {
            var numberOfSlides = slides.length;
            var numberOfDisplay = Math.ceil(numberOfSlides / displayNum);

            slides.hide();

            var slideWrapper = $("#hSohaSlideWrapper");
            slideWrapper.css({
                "width": numberOfSlides * slideWidth + "px",
                "float": "left",
                "position": "relative"
            });

            slideWrapper.wrapAll("<div id='hSohaViewPort'></div>");
            var viewPort = $("#hSohaViewPort");
            viewPort.css({
                "width": slideWidth * displayNum + "px",
                "float": "left",
                "position": "relative",
                "overflow": "hidden",
                "margin-left": "10px"
            });

            slides.show();

            var lis = viewPort.find("li");
            var numberOfLi = lis.length;
            var counterFormat = " {0} - {1} / {2}";

            function changePosition() {
                if (currentPosition == numberOfDisplay - 1) {
                    currentPosition = 0;
                } else {
                    currentPosition++;
                }
                moveSlide();
            }

            function moveSlide() {
                slideWrapper.animate({ 'marginLeft': slideWidth * displayNum * (-currentPosition) });
                $("#hSohaEmbed_SlideCounter").html(String.format(
                            counterFormat,
                            (currentPosition + 1) * 4 - 4 + 1,
                            (currentPosition + 1) * 4 <= numberOfLi ? (currentPosition + 1) * 4 : numberOfLi,
                            numberOfLi
                        ));
            }

            function setCouterStatus() {
                $("#hSohaEmbed_SlideCounter").html(String.format(
                            counterFormat,
                            (currentPosition + 1) * 4 - 4 + 1,
                            (currentPosition + 1) * 4 <= numberOfLi ? (currentPosition + 1) * 4 : numberOfLi,
                            numberOfLi
                        ));
            }
            setCouterStatus();

            function changePositionToLeft() {

                if (currentPosition <= 0) {
                    currentPosition = numberOfDisplay - 1;
                } else {
                    currentPosition--;
                }
                moveSlide();
            }

            function changePositionToLeft() {

                if (currentPosition <= 0) {
                    currentPosition = numberOfDisplay - 1;
                } else {
                    currentPosition--;
                }
                moveSlide();
            }

            var sohaEmbedInterval = setInterval(changePosition, speed);


            $('.hSohaEmbed_box-sohact').hover(
                function () {
                    clearInterval(sohaEmbedInterval);
                },
                function () {
                    sohaEmbedInterval = setInterval(changePosition, speed);
                }
            );

            $('#hSohaEmbed_btnNext').hover(
                        function () {
                            clearInterval(sohaEmbedInterval);
                            $(this).bind('click', changePosition);
                        },
                        function () {
                            $(this).unbind('click');
                            sohaEmbedInterval = setInterval(changePosition, speed);
                        }
                    );

            $('#hSohaEmbed_btnPre').hover(
                        function () {
                            clearInterval(sohaEmbedInterval);
                            $(this).bind('click', changePositionToLeft);
                        },
                        function () {
                            $(this).unbind('click');
                            sohaEmbedInterval = setInterval(changePosition, speed);
                        }
                    );

        }

    }
};


hSohaEmbed.getData();
     